import preferences from '@ohos.data.preferences';
import { OrderModel, UserModel } from '../model/OrderModel';

/**
 * 本地存储管理类
 */
export class StorageManager {
  private static instance: StorageManager;
  private preferencesStore: preferences.Preferences | null = null;

  private constructor() {}

  public static getInstance(): StorageManager {
    if (!StorageManager.instance) {
      StorageManager.instance = new StorageManager();
    }
    return StorageManager.instance;
  }

  /**
   * 初始化存储
   */
  public async init(): Promise<void> {
    try {
      const context = getContext();
      this.preferencesStore = await preferences.getPreferences(context, 'homors_storage');
    } catch (error) {
      console.error('Storage init failed:', error);
    }
  }

  /**
   * 存储工单数据
   */
  public async saveOrders(orders: OrderModel[]): Promise<void> {
    if (!this.preferencesStore) {
      await this.init();
    }
    try {
      await this.preferencesStore?.put('orders', JSON.stringify(orders));
      await this.preferencesStore?.flush();
    } catch (error) {
      console.error('Save orders failed:', error);
    }
  }

  /**
   * 获取工单数据
   */
  public async getOrders(): Promise<OrderModel[]> {
    if (!this.preferencesStore) {
      await this.init();
    }
    try {
      const ordersData = await this.preferencesStore?.get('orders', '[]');
      if (typeof ordersData === 'string') {
        return JSON.parse(ordersData) as OrderModel[];
      }
      return [];
    } catch (error) {
      console.error('Get orders failed:', error);
      return [];
    }
  }

  /**
   * 存储用户信息
   */
  public async saveCurrentUser(user: UserModel): Promise<void> {
    if (!this.preferencesStore) {
      await this.init();
    }
    try {
      await this.preferencesStore?.put('current_user', JSON.stringify(user));
      await this.preferencesStore?.flush();
    } catch (error) {
      console.error('Save user failed:', error);
    }
  }

  /**
   * 获取当前用户信息
   */
  public async getCurrentUser(): Promise<UserModel | null> {
    if (!this.preferencesStore) {
      await this.init();
    }
    try {
      const userData = await this.preferencesStore?.get('current_user', '');
      if (typeof userData === 'string' && userData) {
        return JSON.parse(userData) as UserModel;
      }
      return null;
    } catch (error) {
      console.error('Get user failed:', error);
      return null;
    }
  }

  /**
   * 清除所有数据
   */
  public async clearAll(): Promise<void> {
    if (!this.preferencesStore) {
      await this.init();
    }
    try {
      await this.preferencesStore?.clear();
      await this.preferencesStore?.flush();
    } catch (error) {
      console.error('Clear storage failed:', error);
    }
  }

  /**
   * 存储键值对
   */
  public async setValue(key: string, value: string | number | boolean): Promise<void> {
    if (!this.preferencesStore) {
      await this.init();
    }
    try {
      await this.preferencesStore?.put(key, value);
      await this.preferencesStore?.flush();
    } catch (error) {
      console.error(`Set value ${key} failed:`, error);
    }
  }

  /**
   * 获取值
   */
  public async getValue(key: string, defaultValue: string | number | boolean = ''): Promise<string | number | boolean> {
    if (!this.preferencesStore) {
      await this.init();
    }
    try {
      const result = await this.preferencesStore?.get(key, defaultValue);
      if (typeof result === 'string' || typeof result === 'number' || typeof result === 'boolean') {
        return result;
      }
      return defaultValue;
    } catch (error) {
      console.error(`Get value ${key} failed:`, error);
      return defaultValue;
    }
  }
}